# -*- coding: utf-8 -*-
"""
Created on Mon May 11 03:22:52 2020

@author: Farman
"""


import os
import pathlib



def file_filter(work_dir, file_list_file_ext='.txt', file_pattern='band1-7.tif'):
    '''
    Get files from file list files with extention file_list_file_ext,
    return the filtered files with pattern file_pattern.

    Parameters
    ----------
    work_dir : string
        Path to find file list files.
        
    file_list_file_ext : string, optional
        File extension of file list files. The default is '.txt'.
        
    file_pattern : string, optional
        File pattern to filter files. The default is 'band1-7.tif'.

    Returns
    -------
    Files filtered.

    '''
    work_dir = pathlib.Path(work_dir)
    files = os.listdir(work_dir)
    
    # files in file list file.
    files_in_list = []
    len_ext = len(file_list_file_ext)
    len_pattern = len(file_pattern)
    
    for file in files:
        if len(file) > len_ext and file[-len_ext:].lower() == file_list_file_ext.lower():
            with open(work_dir / file) as f:
                for line in f:
                    line = line.strip()
                    line = line.rstrip()
                    
                    if len(line) > len_pattern and line[-len_pattern:] == file_pattern:
                        files_in_list.append(line)
    print('In [%s]'%work_dir)
    print('Found file list files : %s'%len(files))
    print('with extension : %s'%file_list_file_ext)
    print('Among them,')
    print('found files : %s'%len(files_in_list))
    print('matching pattern : %s'%file_pattern)
    return files_in_list


def save_file_list(file_list, save_file):
    '''
    Save file list to file save_file.

    Parameters
    ----------
    file_list : string list.
        Each item contains a string descripting a (path) name of file.
        
    save_file : string
        Name of file to contain file list.

    Returns
    -------
    None.

    '''
    files = [file + '\n' for file in file_list]
    
    with open(save_file, 'w') as f:
        f.writelines(files)
    
    return


work_dir = '.'
file_list_file_ext = '.txt'
file_pattern = 'sr_band1-7.tif'

files = file_filter(work_dir, file_list_file_ext, file_pattern)
save_file_list(files, 'LandsatDataFiles.list')
